import styles from './Article.module.css'
import { useHistory } from 'react-router-dom'
import { BASE_URL } from '../../constants'
const Article = (props) => {
  const propsCopy = {...props}
  const propertyNames = ['id', 'title', 'category', 'createTime', 'updateTime']
  propertyNames.forEach(property => {
    if (!propsCopy.hasOwnProperty(property)) {
      propsCopy[property] = '空'
    }
  })
  propsCopy['createTime'] = (new Date(propsCopy['createTime']).toLocaleDateString())
  propsCopy['updateTime'] = (new Date(propsCopy['updateTime']).toLocaleDateString())
  const history = useHistory()
  const handleClick = () => {
    fetch(`${BASE_URL}/articles/`+propsCopy.id, {
      method: "DELETE"
    })
    .then(res => res.json())
    .then(res => {
      if (!res.status === "ok") alert("删除失败")
      else {
        alert("删除成功")
        props.flush()
      }
    })
  }
  return (
    <div className={styles.article}>
      <div>{propsCopy.id}</div>
      <div>{propsCopy.title}</div>
      <div>{propsCopy.category}</div>
      <div>{propsCopy.createTime}</div>
      <div>{propsCopy.updateTime}</div>
      <div>
        <button className={styles.btn} onClick={() => history.push("/update/" + propsCopy.id)}>修改</button>
        <button className={styles.btn} onClick={() => handleClick()}>删除</button>
      </div>
    </div>
  )
}

export default Article